package com.hifar.test.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.common.QueryParamBean;
import com.hifar.fw.utils.bean.BusiConst;
import com.hifar.model.VO.QueryParamsVO;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.sys.*;
import com.hifar.test.product.pojo.HfProductBase;
import com.hifar.test.product.service.IHfProductBaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 产品-管理 前端控制器 default
 * </p>
 *
 * @author wangkepeng
 * @since 2024-12-05 14:47:08
 */
@RestController
@RequestMapping("/api/busi/test/hfProductBaseController")
@Api(tags = "产品-管理功能")
public class HfProductBaseController {

    @Autowired
    private IHfProductBaseService hfProductBaseService;


    @PostMapping(value = "/list")
    @ApiOperation(value = "产品-管理功能:分页查询列表")
    public BusiResponse list(@RequestBody @Validated QueryParamsVO queryParamsVO) {
        QueryParamBean<HfProductBase> queryParamBean = new QueryParamBean<>(queryParamsVO);
        QueryWrapper<HfProductBase> queryWrapper = queryParamBean.getQueryWrapper();
        Page<HfProductBase> page = queryParamBean.getPage();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        Page<HfProductBase> pageData = hfProductBaseService.page(page, queryWrapper);
        /*计算分页信息返回给前端*/
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);

    }

    @PostMapping(value = "/listAll")
    @ApiOperation(value = "产品-管理功能:查询列表(不带分页)")
    public BusiResponse listAll(HttpServletRequest request) {
        QueryWrapper<HfProductBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        List<HfProductBase> list = hfProductBaseService.list(queryWrapper);
        if (list != null && list.size() > 0) {
            return BusiResponse.OK(list);
        } else {
            return BusiResponse.ok("没有查询到数据！");
        }
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "产品-管理功能:新增")
    public BusiResponse add(@RequestBody HfProductBase hfProductBase) {
        // 判断编号是否重复add
        QueryWrapper<HfProductBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().ne(HfProductBase::getDelFlag, 1);
        queryWrapper.eq("product_code", hfProductBase.getProductCode());
        queryWrapper.eq("product_name", hfProductBase.getProductName());
        queryWrapper.eq("product_alias", hfProductBase.getProductAlias());
        int count = hfProductBaseService.count(queryWrapper);
        if (count > 0) {
            return BusiResponse.error(400, String.format("产品名称[%s],产品编码[%s],产品代号[%s]已经存在！", hfProductBase.getProductName(), hfProductBase.getProductCode(), hfProductBase.getProductAlias()));
        }
        hfProductBaseService.save(hfProductBase);
        return BusiResponse.ok("添加成功");
    }


    @PostMapping(value = "/edit")
    @ApiOperation(value = "产品-管理功能:编辑")
    public BusiResponse edit(@RequestBody HfProductBase hfProductBase) {

        //判断编号是否重复add
        QueryWrapper<HfProductBase> queryWrapper = new QueryWrapper<HfProductBase>();
        queryWrapper.lambda().ne(HfProductBase::getDelFlag, 1)
                .ne(HfProductBase::getId, hfProductBase.getId());
        queryWrapper.eq("product_code", hfProductBase.getProductCode());
        queryWrapper.eq("product_name", hfProductBase.getProductName());
        queryWrapper.eq("product_alias", hfProductBase.getProductAlias());
        int count = hfProductBaseService.count(queryWrapper);
        if (count > 0) {
            return BusiResponse.error(400, String.format("产品名称[%s],产品编码[%s],产品代号[%s]已经存在！", hfProductBase.getProductName(), hfProductBase.getProductCode(), hfProductBase.getProductAlias()));
        }
        hfProductBaseService.updateById(hfProductBase);
        return BusiResponse.ok("编辑成功！");
    }


    @GetMapping("/queryById")
    @ApiOperation(value = "产品-管理功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam(value = "id") String id) {
        HfProductBase byId = hfProductBaseService.getById(id);
        // 查询转换附件
        return BusiResponse.OK(byId);
    }


    @PostMapping("/delete")
    @ApiOperation(value = "产品-管理功能:逻辑删除")
    public BusiResponse delete(@RequestBody List<String> idList) {
        hfProductBaseService.removeByIds(idList);
        return BusiResponse.ok("删除成功！");
    }

    @PostMapping("/exportExcel")
    @ApiOperation(value = "产品-管理功能:导出数据")
    public Object exportExcel(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        if (pageInfo == null) {
            return BusiResponse.error("参数有误！");
        }
        BusiResponse export = hfProductBaseService.exportExcel(pageInfo);
        if (export.getCode() == BusiConst.CODE_SUCCESS) {
            String encode = null;
            try {
                encode = URLEncoder.encode("产品-管理.xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.add("Content-Disposition", "filename=" + encode);
            return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
        }
        return export;
    }

    @PostMapping("/importExcel")
    @ApiOperation(value = "产品-管理功能:导入excel数据")
    public BusiResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return BusiResponse.error("文件为空！");
        } else {
            if (ExcelTemplateUtil.isExcelFile(file)) {
                return hfProductBaseService.importExcel(file);
            } else {
                return BusiResponse.error("请上传excel文件！");
            }
        }
    }

    @GetMapping("/authProductName")
    public BusiResponse authProductName(@RequestParam(required = false) String productName,
                                        @RequestParam(required = false) String productAlias) {
        QueryWrapper<HfProductBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(" distinct product_name");
        queryWrapper.lambda()
                .eq(StringUtils.hasText(productAlias), HfProductBase::getProductAlias, productAlias)
                .likeRight(StringUtils.hasText(productName), HfProductBase::getProductName, productName)
                .orderByDesc(HfProductBase::getProductName);
        IPage<HfProductBase> page = new Page<>(1, 10);
        IPage<HfProductBase> pageData = hfProductBaseService.page(page, queryWrapper);
        List<HfProductBase> records = pageData.getRecords();
        List<String> productNameList = records.stream()
                .distinct()
                .map(HfProductBase::getProductName)
                .collect(Collectors.toList());
        return BusiResponse.OK(productNameList);
    }

    @GetMapping("/authProductAlias")
    public BusiResponse authProductAlias(@RequestParam(required = false) String productName,
                                         @RequestParam(required = false) String productAlias) {
        QueryWrapper<HfProductBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(" distinct product_alias");
        queryWrapper.lambda()
                .eq(StringUtils.hasText(productName), HfProductBase::getProductName, productName)
                .likeRight(StringUtils.hasText(productAlias), HfProductBase::getProductAlias, productAlias)
                .orderByDesc(HfProductBase::getProductAlias);
        IPage<HfProductBase> page = new Page<>(1, 10);
        IPage<HfProductBase> pageData = hfProductBaseService.page(page, queryWrapper);
        List<HfProductBase> records = pageData.getRecords();
        List<String> productNameList = records.stream()
                .distinct()
                .map(HfProductBase::getProductAlias)
                .collect(Collectors.toList());
        return BusiResponse.OK(productNameList);
    }

}